﻿using System;
using System.Collections.Generic;

using RexToy.UI.WinForm.ViewModel;
using RexToy.UI.WinForm.Pmlx;

namespace RexToy.UI.WinForm.Controls
{
    public class Label : System.Windows.Forms.Label, IDataExchange, IBindCommand
    {
        public Label()
        {
            this.Click += new EventHandler(Label_Click);
            this.Disposed += new EventHandler(Label_Disposed);
        }

        void Label_Disposed(object sender, EventArgs e)
        {
            CommandBindRegistry.Instance().RemoveItem(this);
        }

        void Label_Click(object sender, EventArgs e)
        {
            if (_cmd != null)
                _cmd.Execute();
        }

        public void UpdateModel(ViewModelBase model)
        {
            //Note:Label is readonly, used for display something, so it would not update underlying model.
        }

        public void UpdateView(ViewModelBase model)
        {
            IReflector r = Reflector.Bind(model);
            object val = r.GetPropertyValue(BindPropertyName);
            if (val != null)
                this.Text = val.ToString();
            else
                this.Text = string.Empty;
        }

        private string _bindPorpertyName;
        public string BindPropertyName
        {
            get
            {
                return this.GetBindProperty(_bindPorpertyName);
            }
            set
            {
                _bindPorpertyName = value;
            }
        }

        public UpdateModelTrigger UpdateModelTrigger { get; set; }

        public bool Exchange { get; set; }

        private IUICommand _cmd;
        public IUICommand Command
        {
            get
            {
                return _cmd;
            }
            set
            {
                CommandBindRegistry.Instance().PutItem(this);
                _cmd = value;
            }
        }

        public void QueryCanExecute()
        {
            if (_cmd != null)
                this.Enabled = _cmd.CanExecute();
        }
    }
}
